package org.loofer.ext.utils;

import android.os.Handler;
import android.os.Looper;
import android.util.Printer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

public final class ThreadUtils {
    private static final WeakHashMap<Looper, PrinterWrapper> sLooperPrinters = new WeakHashMap();
    private static Handler sMainHandler = new Handler(Looper.getMainLooper());
    private static Thread sMainThread = Looper.getMainLooper().getThread();

    static final class PrinterWrapper implements Printer {
        private final AtomicBoolean mHasPendingPrinter = new AtomicBoolean(false);
        private final List<Printer> mPendingPrinters = new LinkedList();
        private final List<Printer> mWrappedPrinters = new ArrayList();

        PrinterWrapper() {
        }

        public void println(String x) {
            if (this.mHasPendingPrinter.getAndSet(false)) {
                synchronized (this.mPendingPrinters) {
                    this.mWrappedPrinters.addAll(this.mPendingPrinters);
                    this.mPendingPrinters.clear();
                }
            }
            for (Printer printer : this.mWrappedPrinters) {
                printer.println(x);
            }
        }

        public void add(Printer printer) {
            synchronized (this.mPendingPrinters) {
                this.mPendingPrinters.add(printer);
            }
            this.mHasPendingPrinter.set(true);
        }
    }

    private ThreadUtils() {
    }

    public static void post(Runnable r) {
        sMainHandler.post(r);
    }

    public static void postDelayed(Runnable r, long delayMillis) {
        sMainHandler.postDelayed(r, delayMillis);
    }

    public static void removeCallbacks(Runnable r) {
        sMainHandler.removeCallbacks(r);
    }

    public static void runOnUiThread(Runnable runnable) {
        if (isMainThread()) {
            runnable.run();
        } else {
            post(runnable);
        }
    }

    public static boolean isMainThread() {
        return sMainThread == Thread.currentThread();
    }

    public static Handler getMainHandler() {
        return sMainHandler;
    }

    public static void addLooperPrinter(Printer printer) {
        addLooperPrinter(Looper.myLooper(), printer);
    }

    public static void addLooperPrinter(Looper looper, Printer printer) {
        if (looper == null) {
            throw new RuntimeException("null looper");
        }
        PrinterWrapper wrapper;
        synchronized (sLooperPrinters) {
            wrapper = (PrinterWrapper) sLooperPrinters.get(looper);
            if (wrapper == null) {
                wrapper = new PrinterWrapper();
                sLooperPrinters.put(looper, wrapper);
                looper.setMessageLogging(wrapper);
            }
        }
        wrapper.add(printer);
    }
}
